/**
 * 
 */
package com.base.myproject.client.busi.service;

import java.util.ArrayList;
import java.util.List;

import com.base.myproject.client.busi.system.PrinterSync;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.Debug;
import com.base.myproject.client.tools.SendServlet;
import com.base.myproject.client.ui.Loading;
import com.base.myproject.client.ui.PrintDialog;
import com.base.myproject.client.ui.celleditor.BaseGridEditor;
import com.base.myproject.client.ui.codenamemap.CodeNameMapFactory;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.fx.FxConfig;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

/**
 * 此类负责会员充值的相关操作
 * @author zgw
 *2009-11-5 下午05:04:26
 * javazgw@gmail.com
 */
public class AddFinace implements Listener<BaseEvent>,AsyncCallback<Associator>,RequestCallback{
	String ccode ;
	String systemid;
	String bcodestr;
	Button fincebutton;
	
	 TextField<String> s_cardno;
	 TextField<String> cname;
	 TextField<String> tel;
	 NumberField finance;
	 Dialog d = new Dialog();
	TextField<String> bcode = new TextField<String>();
	TextField<String> pass = new TextField<String>();
	NumberField finacefield_real = new NumberField(); //实际充值金额，就是收到的现金
	NumberField finacefield_gif = new NumberField();//赠送金额，就是充1000送200的那200元
	NumberField finacefield = new NumberField();//总充值金额
	FormPanel formpanel = new FormPanel();
	BaseGridEditor bge2;
	Button getassoc_button;
	public AddFinace()
	{
		
	}
	public AddFinace(String ccode,String systemid,String bcode)
	{
		this.ccode = ccode;
		this.systemid = systemid;
		this.bcodestr = bcode;
	}
		
	public void showDialog()
	{

		d.setWidth("100");
		
		d.setHeading("会员充值");
		
//		final TextField<String> ccode = new TextField<String>();
//		ccode.setAllowBlank(false);
//		ccode.setFieldLabel("用户");
		
		//---
		CodeNameMapFactory cnmf = new CodeNameMapFactory();
//
//		List<ColumnConfig> ccodecolumns = new ArrayList<ColumnConfig>();
//		ColumnConfig ccode = new ColumnConfig("code", "客户编码", 100);
//
//		ccodecolumns.add(ccode);
//
//		ColumnConfig cname = new ColumnConfig("name", "客户名", 50);
//
//		ccodecolumns.add(cname);
//		final BaseGridEditor bge_ccode = new BaseGridEditor(ccodecolumns, cnmf.getBaseccodestore(), "name", "code");
//		bge_ccode.setFieldLabel("客户名");
//	
//		if(this.getCcode()!=null)
//		{
//			
//			for(int i=0;i<CodeNameMapFactory.getBaseccodestore().getCount();i++)
//			{
//				if(this.getCcode().equals(CodeNameMapFactory.getBaseccodestore().getValue(i, "code")))
//				{
//					bge_ccode.setCode(this.getCcode());
//					
//					bge_ccode.setDisplayname(CodeNameMapFactory.getBaseccodestore().getValue(i,"name"));
//					bge_ccode.setValue(CodeNameMapFactory.getBaseccodestore().getValue(i,"name"));
//					break;
//				}
//					
//			}
//			
//		}
		//---
		
		
		
		bcode.setAllowBlank(false);
		bcode.setFieldLabel("操作员");
		
		//----
	//	CodeNameMapFactory cnmf = new CodeNameMapFactory();
		 s_cardno = new TextField<String>();
		s_cardno.setFieldLabel("会员卡号");
		s_cardno.addListener(Events.Change, this);
		
		 cname = new TextField<String>();
		cname.setFieldLabel("会员名");
		cname.addListener(Events.Change, this);
		
		 tel = new TextField<String>();
		tel.setFieldLabel("会员电话");
		tel.addListener(Events.Change, this);
		
		finance= new NumberField();
		finance.setFieldLabel("当前可用余额");
		
		getassoc_button = new Button("获取会员信息");
		getassoc_button.addListener(Events.Select, this);
		
		
		List<ColumnConfig> bocodecolumns2 = new ArrayList<ColumnConfig>();
		ColumnConfig bcode2 = new ColumnConfig("code", "人员", 100);

		bocodecolumns2.add(bcode2);

		ColumnConfig bname = new ColumnConfig("name", "人员名", 50);

		bocodecolumns2.add(bname);
		bge2 = new BaseGridEditor(bocodecolumns2, cnmf
				.getBasebcodestore_canaddfinance(), "name", "code");
		//final TextField<String> bge2 = new TextField<String>();
		bge2.setFieldLabel("操作员");
		bge2.setAllowBlank(false);
		 //----
		
		pass.setAllowBlank(false);
		pass.setFieldLabel("密码");
		pass.setPassword(true);
		
		
		finacefield_real.setAllowBlank(false);
		finacefield_real.setFieldLabel("充值金额");
		finacefield_gif.setToolTip("你实际收到会员的金额");
		
		finacefield_gif.setAllowBlank(false);
		finacefield_gif.setFieldLabel("赠送金额");
		finacefield_gif.setToolTip("如果没有赠送金额，你要录入0");

		finacefield.setAllowBlank(false);
		finacefield.setFieldLabel("总金额");
		finacefield.setToolTip("充值金额 与 赠送金额 的合计");
		
		formpanel.setLabelWidth(75);
		formpanel.setFieldWidth(120);
		formpanel.add(s_cardno);
		formpanel.add(cname);
		formpanel.add(tel);
		formpanel.add(finance);
		formpanel.add(getassoc_button);
	//	formpanel.add(bge_ccode);
		formpanel.add(finacefield_real);
		formpanel.add(finacefield_gif);
		formpanel.add(finacefield);
		
//		formpanel.add(bcode);
		formpanel.add(bge2);
		formpanel.add(pass);
		
//		d.setLayout(new ColumnLayout());
//		d.add(new Label("请录入充值金额"),new ColumnData(0.3));
//		d.add(finacefield,new ColumnData(0.7));
//		
		d.setSize(260, 400);
		d.add(formpanel);
		d.setButtons(Dialog.OKCANCEL);
		//d.setHideOnButtonClick(true);
		
//		d.getButtonById(Dialog.CANCEL).addSelectionListener(new SelectionListener<ButtonEvent>(){
//
//			@Override
//			public void componentSelected(ButtonEvent ce) {
//				d.setVisible(false);
//			}
//		});
		d.getButtonById(Dialog.CANCEL).addListener(Events.Select, this);
		d.getButtonById(Dialog.OK).addListener(Events.Select, this);
		finacefield_real.addListener(Events.Change, this);
		finacefield_gif.addListener(Events.Change, this);
//		d.getButtonById(Dialog.OK).addSelectionListener(new SelectionListener<ButtonEvent>(){
//
//			@Override
//			public void componentSelected(ButtonEvent ce) {
//			
////				if(s_cardno.getValue()==null ||s_cardno.getValue().equals(""))
////				{
////					MessageBox.alert("警告", "会员卡号没有录入", null);
////					return;
////				}
////				if(formpanel.isValid())
////				{
//////					Debug.printf(bge2.getCode(),4);
//////					Debug.printf(bge2.getDisplayname());
//////					Debug.printf(bge_ccode.getCode());
//////					Debug.printf(bge_ccode.getDisplayname());
////					
////				 SendServlet ss = new SendServlet();
////				 try {
////					 
////					ss.sendServlet("/gwtbase/FinaceServlet", "Action=addfince&s_cardno="+s_cardno.getValue()+"&user="+bge2.getValue()+"&pass="+pass.getValue()+"&finace="+finacefield.getValue()+"", null, null,this);
////				} catch (RequestException e) {
////					// TODO Auto-generated catch block
////					e.printStackTrace();
////				}
////				}
////				else 
////				{
////					MessageBox.alert("警告", "内容没有录入完整", null);
////				}
////				
//			}
//			
//		});
		
		d.show();
	}

	public Button getFinceButton()
	{
		fincebutton = new Button();
		fincebutton.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				showDialog();
				
			}
			
		});
		return fincebutton;
	}
	/**
	 * @return the ccode
	 */
	public String getCcode() {
		return ccode;
	}
	/**
	 * @param ccode the ccode to set
	 */
	public void setCcode(String ccode) {
		this.ccode = ccode;
	}
	/**
	 * @return the systemid
	 */
	public String getSystemid() {
		return systemid;
	}
	/**
	 * @param systemid the systemid to set
	 */
	public void setSystemid(String systemid) {
		this.systemid = systemid;
	}
	/**
	 * @return the bcode
	 */
	public String getBcode() {
		return bcodestr;
	}
	/**
	 * @param bcode the bcode to set
	 */
	public void setBcode(String bcode) {
		this.bcodestr = bcode;
	}
	@Override
	public void handleEvent(BaseEvent be) {
		if(be.getSource().equals(s_cardno))
		{
			if(!(s_cardno.getValue()==null || s_cardno.getValue().equals("")) )
			{
			final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
			.create(com.base.myproject.client.tools.GreetingService.class);
			greetingService.getAssociator(s_cardno.getValue(),4,this);
//			 DOM.setInnerHTML(RootPanel.get("Loading-Message").getElement(), "<img src=\"images/baseimage/ajax-loader.gif\"  alt=\"loading\"> Loading GWT Application, please wait...");
			 Loading.getinstance().loading();
			}
			
		}
		else if(be.getSource().equals(finacefield_real)||be.getSource().equals(finacefield_gif))
		{
			
			finacefield.setValue((finacefield_real.getValue()==null?0:finacefield_real.getValue().doubleValue())+(finacefield_gif.getValue()==null?0:finacefield_gif.getValue().doubleValue()));
		}
//		else if(be.getSource().equals(cname))
//		{
//			final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
//			.create(com.base.myproject.client.tools.GreetingService.class);
//			greetingService.getAssociator(cname.getValue(),2,this);
//			 Loading.getinstance().loading();
//		}
//		else if(be.getSource().equals(tel))
//		{
//			final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
//			.create(com.base.myproject.client.tools.GreetingService.class);
//			greetingService.getAssociator(tel.getValue(),3,this);
//			 Loading.getinstance().loading();
//		}
		 if (be.getSource() == getassoc_button) {
			if(!(s_cardno.getValue()==null || s_cardno.getValue().equals("")) )
			{
			final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
			.create(com.base.myproject.client.tools.GreetingService.class);
			greetingService.getAssociator(s_cardno.getValue(),4,this);
			}
			else if(!(cname.getValue()==null || cname.getValue().equals("")) )
			{
				final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
				greetingService.getAssociator(cname.getValue(),2,this);
				 Loading.getinstance().loading();
			}
			else if(!(tel.getValue()==null || tel.getValue().equals("")) )
			{
				final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
				greetingService.getAssociator(tel.getValue(),3,this);
				 Loading.getinstance().loading();
			}
		}
		 else if(be.getSource() == d.getButtonById(Dialog.CANCEL))
		{
			d.setVisible(false);
		}
		else if(be.getSource() == d.getButtonById(Dialog.OK))
		{

			
			if(s_cardno.getValue()==null ||s_cardno.getValue().equals(""))
			{
				MessageBox.alert("警告", "会员卡号没有录入", null);
				return;
			}
			if(formpanel.isValid())
			{
//				Debug.printf(bge2.getCode(),4);
//				Debug.printf(bge2.getDisplayname());
//				Debug.printf(bge_ccode.getCode());
//				Debug.printf(bge_ccode.getDisplayname());
				
			 SendServlet ss = new SendServlet();
			 try {
				 
				ss.sendServlet("/"+GWT.getModuleName()+"/FinaceServlet", "Action=addfince&s_cardno="+s_cardno.getValue()+"&user="+bge2.getCode()+"&pass="+pass.getValue()+"&finace="+finacefield.getValue()+"&finace_real="+finacefield_real.getValue()+"&finace_gif="+finacefield_gif.getValue(), null, null,this);
		
//				设置ok按钮可以被按下，在发送会等待网络的时候ok按钮被禁止
				d.getButtonById(Dialog.OK).setEnabled(false);
			 } catch (RequestException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
			else 
			{
				MessageBox.alert("警告", "内容没有录入完整", null);
			}
			
		
		}
	}
	@Override
	public void onFailure(Throwable caught) {
		
		reset();
		Info.display("提示", "没有找到会员");  
		Loading.getinstance().loaded();
	}

	@Override
	public void onSuccess(Associator result) {
		
		if(result.getName()!=null)
		{
//		associator_no_t.setValue(result.getCcode());
//		associator_name_t.setValue(result.getName());
//		associator_phone_t.setValue(result.getPhone());
//		associator_type_t.setValue(result.getType());
//		associator_jifen_t.setValue(""+result.getJifen());
//		associator_finance_t.setValue(""+result.getFinance());
			cname.setValue(result.getName());
			s_cardno.setValue(result.getS_cardno());
			tel.setValue(result.getPhone());
			finance.setValue(result.getFinance());
		}
		else
		{
			
			reset();
			Info.display("提示", "没有找到会员");  
			
		}
		Loading.getinstance().loaded();
	}
	@Override
	public void onError(Request request, Throwable exception) {
		Info.display("","操作失败!!");
		d.el().blink(FxConfig.NONE);  
		
	}

	@Override
	public void onResponseReceived(Request request,
			Response response) {
		Document doc = XMLParser.parse((String) response
					.getText());
			NodeList list = doc.getElementsByTagName("root");
			Node node = list.item(0);
			Element elem = (Element) node;

			if (elem.getAttribute("status").equals(
					Env.SUCCESS)) {
				// MessageBox.info("", "注册成功", null);
				addfinancesuccess(elem);
				printer();
			} else {
				Info.display("","操作失败!!"+elem.getAttribute("message") );
				d.el().blink(FxConfig.NONE);  
//				设置ok按钮可以被按下，在发送会等待网络的时候ok按钮被禁止，此处取消禁止
				d.getButtonById(Dialog.OK).setEnabled(true);
			}
		
	}
	 
protected void  addfinancesuccess(Element elem )
{
	Info.display("", "会员" + elem.getAttribute("cname") + "充值操作成功");
	String finance = elem.getAttribute("addfinance");
	String lastfinance = elem.getAttribute("lastfinance");
	String s_cardno = elem.getAttribute("s_cardno");
	String name = elem.getAttribute("cname");
	// int display=5000;//X秒关闭
	// InfoConfig config = new
	// InfoConfig(display/1000+"秒后自动关闭","会员："+name+"\n卡号："+s_cardno+"\n此次充值金额："+finance+"\n资金余额："+lastfinance+"\n充值操作成功"
	// );
	// config.display = display;
	// Info.display(config);
	d.setVisible(false);
//	设置ok按钮可以被按下，在发送会等待网络的时候ok按钮被禁止，此处取消禁止
	d.getButtonById(Dialog.OK).setEnabled(true);

	Dialog simple = new Dialog();
	simple.setHeading("充值操作成功");
	// simple.setButtons(Dialog.YESNO);
	simple.setBodyStyleName("pad-text");
	simple.addText("会员：" + name + "<br>卡号：" + s_cardno + "<br>此次充值金额："
			+ finance + "<br>资金余额：" + lastfinance + "<br>充值操作成功");

	simple.setHideOnButtonClick(true);
	simple.show(); 
}
	
	private void reset()
	{
		cname.setValue("");
		s_cardno.setValue("");
		tel.setValue("");
		finance.setValue(0);
	}
	

	private void printer()
	{
		if(s_cardno.getValue()==null || s_cardno.getValue()=="")
		{
			MessageBox.alert("错误", "没找到会员卡号，请在 “会员管理” 模块进行打印", null);
			return;
		}
		PrinterSync printersync = new PrinterSync();
		printersync.setBcode(Env.getEnvbcode());
		printersync.setPrintcode("service_1002");
		printersync.setIcode(s_cardno.getValue()+"");
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
		.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getPrinterHtml(printersync,new AsyncCallback<String>(){

			@Override
			public void onFailure(Throwable caught) {
				
				
			}

			@Override
			public void onSuccess(String result) {
				Debug.printf(result.toString());
				PrintDialog print = new PrintDialog("", "", result);
			}
			
		});
	}
}
